import os
import time

import requests,json,datetime
# 预定自习室
class OrderLibraryRoom:
    session = requests.Session()
    # 预约房间号
    roomId = 21 # 默认21
    roomMap = {
        6 : "研讨室319",
        9 : "研讨室443",
        10: "研讨室444",
        11: "研讨室407",
        12: "研讨室406",
        13: "研讨室426",
        14: "研讨室427",
        15: "研讨室428",
        16: "研讨室429",
        17: "研讨室430",
        18: "研讨室431",
        19: "研讨室432",
        20: "研讨室433",
        21: "研讨室434",
        22: "研讨室435"
    }

    orderTime = ""
    otherUser = ""
    # 用户集合
    userMap = {}
    # 需要预约的日期， 2为后天
    # orderDay = str(datetime.date.today() + datetime.timedelta(days=2))
    orderDay = str(datetime.date.today()+ datetime.timedelta(days=1))
    # 登陆账号
    loginLibraryUrl = r"https://libseminarroom.bjut.edu.cn/login"
    # 获取房间信息网址
    getRoomUrl = "https://libseminarroom.bjut.edu.cn/reservation/list"
    # 主要用来检查 参与人与申请人是否不同以及参与人是否存在
    checkUserUrl = "https://libseminarroom.bjut.edu.cn/reservation/checkrule"
    ##  提交预约数据
    orderRoomUrl = "https://libseminarroom.bjut.edu.cn/reservation/save"
    headers = {
        "Referer": "https://libseminarroom.bjut.edu.cn/reservation?areaId=21",
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    orderResFile = open(orderDay + ".txt", "w")
    def __init__(self,userMap,orderTime,otherUser,roomId):
        self.userMap = userMap
        self.orderTime = orderTime
        self.otherUser = otherUser
        self.roomId = roomId

        print("----当前预约时间为：{} ----".format(self.orderDay),file=self.orderResFile )
    def loginLibrary(self):

        self.session.keep_alive = False
        # 获取登陆成功信息，code = 0 则为登陆成功，登陆成功返回结果为字符串，json.loads将其转化为json，方便获取其code值
        resPost = self.session.post(self.loginLibraryUrl, data=self.userMap, headers=self.headers).text  # 此处获取的是post过来的json数据
        jsonData=  json.loads(resPost)
        if jsonData["code"] == 0:
            print("---登陆成功，当前登陆账号为:{}---".format(self.userMap["loginname"]),file=self.orderResFile)
        else:
            print("---登陆失败，失败信息为:{}---{}".format(jsonData["msg"],self.userMap["loginname"]),file=self.orderResFile)
            return ""
            exit(0)

    # 预定房间
    def orderRoom(self):
        subFromData = {
            "applyNo": '20190511-0001',
            "roomId": self.roomId,
            "roomPurposeId": 6,
            "otherUser": self.otherUser,  # 18371217
            "applydate": self.orderDay,
            "applytime": self.orderTime
        }

        # 最终提交预约信息
        res = json.loads(self.session.post(url=self.orderRoomUrl, data=subFromData, headers=self.headers).text)
        # 显示预约信息
        subFromData["roomId"] = self.roomMap[subFromData["roomId"]]

        print(subFromData,file=self.orderResFile)
        if res['code'] == 0:
            print("\t\t\t\t\t\t", res['msg'],file=self.orderResFile)
            print("预约时间为：", self.orderDay, subFromData["applytime"],file=self.orderResFile)
        else:
            print("\t\t\t\t\t\t", "预约失败",file=self.orderResFile)
            print(res['msg'],file=self.orderResFile)
    # 获取预约列表
    def getOrderList(self):
        # 查看 预约list
        res = json.loads(self.session.post(url="https://libseminarroom.bjut.edu.cn/reservation/mylist", headers=self.headers).text)

        print("\t\t\t\t\t\t", "预约列表",file=self.orderResFile)
        for d in res['data']:
            print("预约id{}\t房间号：{}\t时间：{}  {}-{}\t参加人{}\t状态：{}".format(d['ReservationID'], d['RoomName'], d['BookDate'],
                                                               d['BeginTime'], d['EndTime'], d["takeIn"],d['ResStateName']),file=self.orderResFile)
    # 运行预约脚本
    def runOrder(self):
        self.loginLibrary()
        self.orderRoom()
        # self.getOrderList()
if __name__ == '__main__':
    # 当前文件运行路径
    path = os.getcwd()
    jsonFile = path + "/config.json"
    # 读取json文件内容
    with open(jsonFile, 'r') as f:
        jsonDate = json.load(f)
    userMap = jsonDate['userMap']
    orderTime = jsonDate['orderTimeList']
    otherUser = jsonDate['otherUser']
    roomIdList = jsonDate['roomId']
    for user , orderT,other,roomId in zip(userMap,orderTime,otherUser,roomIdList):
        loginUser = {
            "loginname": user,
            "password": userMap[user],
        }
        # print(loginUser,orderT,other)
        Library = OrderLibraryRoom(loginUser,orderT,other,roomId=roomId)
        Library.runOrder()
